/*
 * @Title Server.java
 * @Description
 * @Copyright Copyright(c) 2018
 * @Company com.lizhen
 * @author lizhen
 * @version 0.0.1
 */
package com.lizhen.nio.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author lizhen
 */
public class Server {

    /**
     * @author lizhen
     */
    public Server() {
    }

    /**
     * @author lizhen
     */
    public static void main(String[] args) {
        TimeServer.main(null);
    }

    static class TimeServer {
        private static int port = 8125;
        private static Charset charset = Charset.forName("US-ASCII");
        private static CharsetEncoder encoder = charset.newEncoder();

        private static ServerSocketChannel setup() {
            ServerSocketChannel ssc = null;
            try {
                ssc = ServerSocketChannel.open();
                String host = InetAddress.getLocalHost().getHostAddress();

                System.out.println("Listen at Host:" + host + ", port:" + port);

                InetSocketAddress isa = new InetSocketAddress(host, port);
                ssc.socket().bind(isa);
                return ssc;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return ssc;
        }

        private static void serve(ServerSocketChannel ssc) {
            SocketChannel sc = null;
            try {
                sc = ssc.accept();
                String now = new Date().toString();
                sc.write(encoder.encode(CharBuffer.wrap(now + "\r\n")));

                System.out.println(sc.socket().getInetAddress() + " : " + now);

                sc.close();
            } catch (CharacterCodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // Make sure we close the channel (and hence the socket)
                if (sc != null) {
                    try {
                        sc.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public static void main(String[] args) {
            if (args != null && args.length > 1) {
                System.err.println("Usage: java TimeServer [port]");
                return;
            }
            if ((args != null && args.length == 1) && Pattern.matches("[0-9]+", args[0]))
                port = Integer.parseInt(args[0]);
            ServerSocketChannel ssc = setup();
            for (; ; )
                serve(ssc);
        }

    }

}